const requestPermission = (permissionID) => {
    return new Promise((resolve, reject) => {
        plus.android.requestPermissions(
            [permissionID],
            function (resultObj) {
                var result = 0;
                for (var i = 0; i < resultObj.granted.length; i++) {
                    var grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限：' + grantedPermission);
                    result = 1;
                }
                for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                    var deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限：' + deniedPresentPermission);
                    result = 0;
                }
                for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                    var deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
                    result = -1;
                }
                resolve(result);
            },
            function (error) {
                console.log('申请权限错误：' + error.code + ' = ' + error.message);
                reject(error);
            }
        );
    });
};

export async function requestPermissions(permissionIDs) {
    // 不要同时授权多个权限，否则可能会被安卓系统认定为恶意应用，直接永久拒绝所有申请。
    for (let i = 0; i < permissionIDs.length; i++) {
        let permissionID = permissionIDs[i];
        let result = await requestPermission(permissionID);
        if (result !== 1) {
            throw new Error(permissionID + '未获得授权或被永久拒绝权限');
        }
    }
}

export async function checkPermissons() {
    // 权限ID数组
    const permissionIDs = [
        'android.permission.READ_EXTERNAL_STORAGE',
        'android.permission.WRITE_EXTERNAL_STORAGE'
        // 在此添加更多需要的权限。初始化PDA方法至少需要文件读写权限。
    ];
    try {
        await requestPermissions(permissionIDs);
        return true;
    } catch (e) {
        uni.showModal({
            title: '权限被拒绝',
            content: '缺少必要的权限，请点击重新授权，若无法自动调起权限请求，请到设置页面自行添加权限或者重装应用。',
            showCancel: true,
            cancelText: '退出应用',
            confirmText: '重新授权',
            success: (res) => {
                if (res.confirm) {
                    checkPermissons();
                } else {
                    plus.runtime.quit();
                }
            },
            fail: () => {
                plus.runtime.quit();
            }
        });
        return false;
    }
}